<?php

/**
 * SearchController
 * 
 * @author
 * @version 
 */

require_once 'Zend/Controller/Action.php';

class SearchController extends Zend_Controller_Action {
	
	private $book;
	private $searchDataCache;
	private $logger;
	
	public function init() {
	   $this->book = new Book();
	   $this->searchDataCache = new SearchDataCache();
	   $this->logger = Zend_Registry::get("logger");
	   $this->_flashMessenger = $this->_helper->getHelper('FlashMessenger');
	   $this->initView();
	   $this->view->flashmsgs = $this->_flashMessenger->getMessages();
	}
	
	/**
	 * The default action - show the home page
	 */
	public function indexAction() {
		// TODO Auto-generated SearchController::indexAction() default action
	}

    /**
     * Reindex.
     * Example: ctl 1686825444, crc e233847ad0507ae1d0890633ced692b9
     */
    public function reindexAction() {
        $this->_helper->viewRenderer->setNoRender();   //view info disabled
        $this->_helper->layout->disableLayout();
        
        $ctl = $this->_getParam('ctl');
        $crc = $this->_getParam('crc');
        $customerKey = '';
        
        $generated_crc = md5($ctl);            
        if ($generated_crc == $crc) {
	        // index for inviatation
	        $books = $this->book->findAllActive();
	        SearchIndexer::setIndexDirctory('book');
	//        Zend_Search_Lucene_Analysis_Analyzer::setDefault(new CN_Lucene_Analyzer());
	        $index = Zend_Search_Lucene::create(SearchIndexer::getIndexDirectory());
	        $index->setMaxBufferedDocs(10);
	        $index->setMaxMergeDocs(PHP_INT_MAX);
	        $index->setMergeFactor(10);
	        foreach($books as $book) {
	            $class = 'Book';
	            $doc = SearchIndexer::getDocument('Book', $book);
	            SearchIndexer::_addToIndex($index, $doc);               
	        }
	        
	        $index->commit();
	        $index->optimize();
	        echo "Lucene index finished, ".count($books)." entries reindexed.";
	        $this->logger->log("Lucene index finished, ".count($books)." entries reindexed.", Zend_Log::INFO);
        }
    }
    
    /**
     * Expire search keys.
     * ctl 8791671 crc 8a0e8903056d5409dc5f84acfdf51933
     */
    public function expiresearchkeywordsAction() {
        $this->_helper->viewRenderer->setNoRender();   //view info disabled
        $this->_helper->layout->disableLayout();
        
        $ctl = $this->_getParam('ctl');
        $crc = $this->_getParam('crc');
        $customerKey = '';
        
        $generated_crc = md5($ctl);            
        if ($generated_crc == $crc) {
        	$db = Zend_Registry::get("db");
        	$db->beginTransaction();
        	$this->searchDataCache->expireSearchData($this->_helper->generator->generateCurrentTime());
        	$db->commit();
        	
        	$this->logger->log("Search keys refreshed!", Zend_Log::INFO);
        }
    }
}

